package data

import (
	"context"
	"go-graduation/service/cmd/cfg"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"time"
)

// Data .
type Data struct {
	db *gorm.DB
}

// NewDBClient 创建一个 Mysql 服务。
func NewDBClient() *gorm.DB {
	config, _ := cfg.ReadConfig()
	db := NewDataBase(config)
	_, _, _ = NewData(db)

	return db
}

func NewDataBase(conf *cfg.Config) *gorm.DB {
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	db, err := gorm.Open(mysql.New(mysql.Config{DSN: conf.Data.MySql.Dsn()}))
	if err != nil {
		panic(err)
	}
	db.WithContext(ctx)
	return db
}

func NewData(database *gorm.DB) (*Data, func(), error) {
	d := &Data{
		db: database,
	}
	return d, func() {
		db, _ := d.db.DB()
		if err := db.Close(); err != nil {
			log.Println(err)
		}
	}, nil
}
